package com.mohistmc.banner.gradle

import com.mohistmc.banner.gradle.task.BuildSpigotTask
import com.mohistmc.banner.gradle.task.DownloadBuildToolsTask
import org.gradle.api.Plugin
import org.gradle.api.Project

class BannerGradlePlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {

        def bannerExt  = project.extensions.create('banner', BannerExtension, project)
        def bannerRepo = project.rootProject.file("${Project.DEFAULT_BUILD_DIR_NAME}/banner_repo")
        project.repositories.maven {
            name = "Banner Spigot Repo"
            url = bannerRepo
        }

        project.afterEvaluate {
            setupSpigot(project, bannerRepo)
        }
    }

    private static def setupSpigot(Project project, File bannerRepo) {
        def bannerExt = project.extensions.getByName('banner') as BannerExtension
        def buildTools = project.rootProject.file("${Project.DEFAULT_BUILD_DIR_NAME}/banner_cache/buildtools")
        def buildToolsFile = new File(buildTools, 'BuildTools.jar')
        def spigotDeps = new File(bannerRepo, "com/mohistmc/banner/generated/spigot/${bannerExt.mcVersion}")
        def spigotMapped = new File(spigotDeps, "spigot-${bannerExt.mcVersion}-mapped.jar")
        def spigotDeobf = new File(spigotDeps, "spigot-${bannerExt.mcVersion}-deobf.jar")

        project.logger.lifecycle(":step1 download build tools")
        def downloadSpigot = new DownloadBuildToolsTask()
        downloadSpigot.output = buildToolsFile
        downloadSpigot.run()

        project.logger.lifecycle(":step2 build spigot")
        def buildSpigot = new BuildSpigotTask(project)
        buildSpigot.outputDir = spigotDeps
        buildSpigot.workDir = buildTools
        buildSpigot.mcVersion = bannerExt.mcVersion
        buildSpigot.buildTools = buildToolsFile
        buildSpigot.run()

        new LocalM("io.izzel.arclight.generated", "spigot", arclightExt.mcVersion, null, arclightRepo.toPath()).savePom()

    }
}
